package org.mili.ticketeer.ui.meeting;

import org.mili.ticketeer.dto.Contact;
import org.mili.ticketeer.dto.ContactMeeting;
import org.mili.ticketeer.dto.Meeting;
import org.mili.ticketeer.service.MeetingService;
import org.mili.application.service.ServiceException;
import org.mili.application.service.ServiceFactory;
import org.mili.application.ui.ManyToManyTableModel;

import java.util.ArrayList;
import java.util.List;

/**
 */
public class ContactMeetingTableModel extends ManyToManyTableModel<Contact, ContactMeeting> {
    private static MeetingService meetingService = ServiceFactory.getService(MeetingService.class);
    private Contact contact;

    public ContactMeetingTableModel() {
        super(new String[]{"No.", "Included?", "Date"});
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        ContactMeeting contactMeeting = get(rowIndex);
        System.out.println("--> " + contactMeeting);
        switch(columnIndex) {
            case 0:
                return rowIndex + 1;
            case 1:
                return contactMeeting.getContact() > 0;
            case 2:
                try {
                    Meeting meeting = meetingService.getMeetingById(contactMeeting.getMeeting());
                    return meeting.getDate();
                } catch (ServiceException e) {
                    return "ERROR";
                }

            default: throw new IllegalStateException("no column index for: " + columnIndex);
        }
    }

    public void setValueAt(Object value, int row, int col) {
        try {
            Boolean set = (Boolean) value;
            ContactMeeting contactMeeting = get(row);
            Meeting meeting = meetingService.getMeetingById(contactMeeting.getMeeting());
            if (set) {
                meetingService.assign(contact, meeting);
            } else {
                meetingService.unassign(contact, meeting);
            }
            update(contact);
//            fireModelChange(contact, contactMeeting);
        } catch (ServiceException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<ContactMeeting> load(Contact contact) {
        this.contact = contact;
        try {
            if (contact == null) {
                return new ArrayList<>();
            } else {
                return meetingService.getAllMeetings(contact);
            }
        } catch (ServiceException e) {
            throw new IllegalStateException(e);
        }
    }

}
